package com.business.redis.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 获取redis key
 */
public class RedisKeysUtil {

    private static final Logger logger = LoggerFactory.getLogger(RedisKeysUtil.class);
    //分割符
    private final static char SEGMENTER = ':';

    /**
     * 获取redis key
     *
     * @param cls     类
     * @param objects 可变参数
     * @return
     */
    public static String getKey(Class cls, Object... objects) {
        String className = cls.getName();
        return getKey(className, objects);
    }

    public static String getKey(String className, Object... objects) {
        StringBuilder stringBuilder = new StringBuilder(className);

        for (Object obj : objects) {
            if (obj != null) {
                stringBuilder.append(SEGMENTER).append(obj);
            }
        }
        return stringBuilder.toString();
    }

    public static String getKey(Class o) {
        return o.getName();
    }

    public static String getKey(Object o) {
        String className = o.getClass().getName();
        try {
            return className + ":" + ObjectUtil.getNotNullFieldToString(o);
        } catch (IllegalAccessException e) {
            logger.error(e.getMessage(), e);
            return className + ":" + o.toString();
        }
    }

}
